package com.entrogy.controller;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.config.Result;
import com.entrogy.service.DepartmentService;
import com.entrogy.service.SchoolService;
import com.entrogy.service.UserService;
import com.entrogy.utils.ApiReturnUtil;
import com.entrogy.utils.BDFaceDetect;
import com.entrogy.utils.IdGenetor;
import com.entrogy.utils.ZoomImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xlr
 * @date 2018-12
 * @description 学校的相关操作
 */
@Api(description = "对学校的相关操作接口")
@RestController
@RequestMapping(value = "/schoolcontroller")
public class SchoolController {

	private static final Logger logger = LoggerFactory.getLogger(SchoolController.class);

	//图片存放根路径
	@Value("${image.root.path}")
	private String rootPath;
	@Value("${show.image.url}")
	private String showImage;
	@Autowired
	private SchoolService schoolService;
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private UserService userService;

    @ApiOperation(value = "添加一个对应市区的学校，学校编号是区编号加固定的5位数字")
	/*@ApiImplicitParams({
			@ApiImplicitParam(name="schoolCode",value = "学校编号(对应的区编号即code值)",required = false,dataType = "Integer",paramType = "query"),
			@ApiImplicitParam(name="schoolName",value = "学校名称",required = false,dataType = "String",paramType = "query")
	})*/
//	@ApiImplicitParam(value = "学校实体类",required = false,dataType = "SchoolEntity")
	@RequestMapping(value = "/insertschool",method = RequestMethod.POST)
//	@RequiresPermissions("school:add")
	public Map<String,Object> insertSchool(@ModelAttribute(value="schoolEntity") SchoolEntity schoolEntity){
		Integer codeDB = schoolService.getSchoolCode(schoolEntity.getSchoolCode());//查出最后一个学校的后三位流水编码
		String schoolCode = "";
		if(codeDB == null){
			schoolCode = String.valueOf(schoolEntity.getSchoolCode())+"000";
		}else{
			String codeStr = String.valueOf(codeDB);
			codeDB = Integer.parseInt(codeStr.substring(codeStr.length()-3,codeStr.length())) + 1;//后截取后三位 之加1
			if(codeDB>=0 && codeDB <=9){
				schoolCode = String.valueOf(schoolEntity.getSchoolCode())+"00"+codeDB;
			}else if(codeDB>=10 && codeDB<=99){
				schoolCode = String.valueOf(schoolEntity.getSchoolCode())+"0"+codeDB;
			}else {
				schoolCode = String.valueOf(schoolEntity.getSchoolCode())+codeDB;
			}
		}
		schoolEntity.setSchoolCode(Integer.parseInt(schoolCode));
		int code = schoolService.insertSchool(schoolEntity);
		if(code == 1){
			departmentService.insertPositions(Integer.parseInt(schoolCode));
			return ApiReturnUtil.success("新增学校成功",null);
		 }else {
         	return ApiReturnUtil.error("新增学校失败");
		 }
	}

	@ApiOperation(value = "根据用户ID查询出其创建的所有学校")
	@RequestMapping(value = "/getSchoolByUserId",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "query")
	})
	public Result<PageBean> getSchoolByUserId(String userId, int schoolCode, String schoolName,Integer  currentPage,Integer pageSize){
		//获取学校id
		UserEntity userEntity=(UserEntity)(SecurityUtils.getSubject().getSession().getAttribute("currentUser"));
		List<SchoolEntity> list=new ArrayList<>();
		Map<String,Object> map=new HashMap<>();
		int  counts=0;
		if (schoolName!=null && !"".equals(schoolName)){
			map.put("schoolName",schoolName);
		}
		if (currentPage!=null && !"".equals(currentPage)){
			map.put("page",(currentPage-1)*pageSize);
		}
		if (pageSize!=null && !"".equals(pageSize)){
			map.put("total",pageSize);
		}
		if (userEntity!=null){
			if (userEntity.getSchoolCode()!=1){
				list = schoolService.getSchoolByUserId(userId);
				if (list.size()==1){
					counts=1;
				}
			}
			else{
				list=schoolService.getSchoolList(map);
				counts=schoolService.getSchoolListByTotal(map);

			}
		}

       return new Result<PageBean>().getResult(401,"查询成功",1,new PageBean<SchoolEntity>().pageBeans(list,counts));
	}

	@ApiOperation(value = "根据学校编码修改其对应的学校信息")
	@RequestMapping(value = "updateSchool",method = RequestMethod.POST)
//	@RequiresPermissions("school:update")
	public Map<String,Object> updateSchool(@ModelAttribute SchoolEntity schoolEntity){
		int code = schoolService.updateSchool(schoolEntity);
		if(code == 1){
			return ApiReturnUtil.success("修改成功",null);
		}else {
			return ApiReturnUtil.error("对不起,网络异常请稍后重试.");
		}
	}

	@ApiOperation(value = "根据学校编码删除其对应的学校信息")
	@RequestMapping(value = "deleteSchool",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "schoolCode", value = "学校编码", required = true, dataType = "Integer", paramType = "query")
	})
//	@RequiresPermissions("school:delete")
	public Map<String,Object> deleteSchool(Integer schoolCode){
		int code = schoolService.deleteSchool(schoolCode);
		if(code == 1){
			return ApiReturnUtil.success("删除成功",null);
		}else {
			return ApiReturnUtil.error("对不起,网络异常请稍后重试.");
		}
	}


	@ApiOperation(value = "查询出其创建的所有学校")
	@RequestMapping(value = "/getSchoolByList",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "query")
	})
//	@RequiresPermissions("school:list")
	public List<SchoolEntity> getSchoolByList(String userId, int schoolCode, String schoolName){
		//获取学校id
		UserEntity userEntity=(UserEntity)(SecurityUtils.getSubject().getSession().getAttribute("currentUser"));
		Map<String,Object> map=new HashMap<>();
		List<SchoolEntity> list=new ArrayList<>();
		if (schoolName!=null && !"".equals(schoolName)){
			map.put("schoolName",schoolName);
		}
		if (userEntity!=null){
			if (userEntity.getSchoolCode()!=1){
				list = schoolService.getSchoolByUserId(userId);

			}
			else{
				list=schoolService.getSchoolList(map);

			}
		}
		return list;
	}


	@ApiOperation(value = "查询出其创建的所有学校")
	@RequestMapping(value = "/getSchoolList",method = RequestMethod.GET)
	@ApiImplicitParams({

	})
//	@RequiresPermissions("school:list")
	public Result getSchoolList(){
		Map<String,Object> map=new HashMap<>();
		List<SchoolEntity> list=schoolService.getSchoolList(map);
		return  new Result<SchoolEntity>().getResult(401, "操作成功", 1, list);
	}

    @ApiOperation(value = "学校banner图设置包括新增和修改(调用上传图片的接口name=banner)")
	@ApiImplicitParams({
			@ApiImplicitParam(name="type",value = "操作类型（1--修改banner图0--新增banner图）",paramType = "query",dataType = "int"),
			@ApiImplicitParam(name="id",value = "修改接口需要带过来的banner图ID",paramType = "query",dataType = "Integer"),
			@ApiImplicitParam(name = "imgUrl",value = "学校bannerUrl",paramType = "query",dataType = "String")
	})
	@RequestMapping(value = "bannerset",method = RequestMethod.POST)
	public Map<String,Object> bannerSet(int type, Integer id,String imgUrl){
		if (imgUrl == null){
			return ApiReturnUtil.error("添加失败，您尚未选中任何图片！");
		}
          int code = schoolService.insertBanner(type,id,imgUrl);
		  if(code == 0){
		  	return ApiReturnUtil.error("对不起,网络异常");
		  }
          return ApiReturnUtil.success("操作成功","");
	}

	@ApiOperation(value = "学校banner图的获取")
	@RequestMapping(value = "getbanner",method = RequestMethod.GET)
	public Map<String,Object> getBanner(){
		Map<String,Object> returnMap = new HashMap<>();
		int schoolCode = (int) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
		List<BannerEntity>  bannerEntities = schoolService.getBanner(schoolCode);
		returnMap.put("code",1);
		returnMap.put("msg","获取成功");
		returnMap.put("data",bannerEntities);
		returnMap.put("showImage",showImage);
        return returnMap;
	}

	@ApiOperation(value = "学校banner图的删除")
	@ApiImplicitParam(value = "banner图ID",name = "id",paramType = "query",dataType = "int",required = true)
	@RequestMapping(value = "deletebanner",method = RequestMethod.DELETE)
	public Map<String,Object> deleteBanner(int id){
         int code = schoolService.deleteBanner(id);
         return ApiReturnUtil.success("删除成功","");
	}

	@ApiOperation(value = "学校banner图上传（在data中返回上传成功后的图片路径）")
	@ApiImplicitParam(name = "name",value = "文件夹名称(命名规范点比如：学校banner图上传,name=banner)",paramType = "String",dataType = "query",required = true)
	@RequestMapping(value = "/upload",method = RequestMethod.POST)
	public Map<String,Object> registorMethod(MultipartFile file, String name){
		try {
			int schoolCode = (int) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
			String fileName = "";
			File path = new File(rootPath+File.separator+schoolCode+File.separator+name);
			if (!path.exists()) {
				path.mkdirs();
			}
			fileName = file.getOriginalFilename();
			File out = new File(path, fileName);
			file.transferTo(out);
			return ApiReturnUtil.success("上传成功",schoolCode+File.separator+name+File.separator+fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiReturnUtil.error( "亲,网络异常哟.");
	}

	@ApiOperation(value = "查询所有学校列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name="selectSchoolCode",value = "操作类型（1--修改banner图0--新增banner图）",paramType = "query",dataType = "int"),
	})
	@GetMapping(value = "/listSchool")
	public Msg listSchool(Integer selectSchoolCode){
		List<JSONObject> schoolList = schoolService.listSchool(selectSchoolCode);
		return Msg.success().add("schoolList", schoolList);
	}

	@ApiOperation(value = "查询学校名称")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid", value = "用户id", paramType = "query", dataType = "String"),
	})
	@GetMapping(value = "/getSchoolName")
	public Msg getSchoolName(String uid){
		Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		String schoolName = schoolService.getSchoolName(schoolCode);
		return Msg.success().add("schoolName", schoolName);
	}

//	@ApiOperation(value = "查询所有学校列表")
//	@GetMapping(value = "/listSchool")
//	public Msg listSchool(){
//		List<JSONObject> schoolList = schoolService.listSchool();
//		return Msg.success().add("schoolList", schoolList);
//	}
}
